package com.example.cookweather;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cookweather.db.City;
import com.example.cookweather.db.RequestData;
import com.example.cookweather.util.HttpUtil;
import com.example.cookweather.util.JsonUtil;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {

    private static final String TAG = "ChooseAreaFragment";

    private static final String cityUrl="https://j.i8tq.com/weather2020/search/city.js";






    private ProgressDialog progressDialog;

    private TextView titleText;

    private Button backButton;

    private ListView listView;

    private ArrayAdapter<String> adapter;

    private List<String> dataList = new ArrayList<>();

    /**
     * 所有数据
     */
    private List<City> cityAllList = new ArrayList<City>();


    /**
     * 市列表
     */
    private List<City> cityList;



    /**
     * 选中的省份
     */
    private City selectedProvince;

    /**
     * 选中的城市
     */
    private City selectedCity;

    /**
     * 选中的城市
     */
    private City selectedCounty;

    /**
     * 当前选中的级别
     */
    private City.CityType currentLevel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view=inflater.inflate(R.layout.choose_area,container,false);
        titleText =(TextView) view.findViewById(R.id.title_text);
        backButton=(Button) view.findViewById(R.id.back_button);
        listView=(ListView) view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (currentLevel == City.CityType.province) {
                    selectedProvince = cityList.get(position);

                    queryCities();
                } else if (currentLevel == City.CityType.city) {
                    selectedCity = cityList.get(position);

                    queryCounties();
                }else if (currentLevel == City.CityType.country){
                    selectedCounty= cityList.get(position);
                    String weatherId=selectedCounty.getId();
                    if (getActivity() instanceof MainActivity) {
                        Intent intent = new Intent(getActivity(), WeatherActivity.class);
                        intent.putExtra("weather_id", weatherId);
                        startActivity(intent);
                        getActivity().finish();
                    } else if (getActivity() instanceof WeatherActivity) {
                        WeatherActivity activity = (WeatherActivity) getActivity();
                        activity.drawerLayout.closeDrawers();
                        //activity.swipeRefresh.setRefreshing(true);
                        activity.requestWeather(weatherId);
                    }
                    Toast.makeText(getContext(), selectedCounty.getName()+selectedCounty.getId(), Toast.LENGTH_SHORT).show();

                }
            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(currentLevel == City.CityType.country){
                    queryCities();
                }else if(currentLevel ==City.CityType.city){
                    queryProvinces();
                }
            }
        });
        queryProvinces();

    }

    /**
     * 查询全国所有的省，优先从数据库查询，如果没有查询到再去服务器上查询。
     */
    @SuppressLint("NewApi")
    private  void queryProvinces(){
        titleText.setText("中国");
        backButton.setVisibility(View.GONE);//意思是不可见的，不占用原来的布局空间


       // cityList = cityAllList.where("cityType=?", City.CityType.province.ordinal()+"").find(City.class);
        cityList = cityAllList.stream().filter(item -> item.getCityType()==City.CityType.province.ordinal()).collect(Collectors.toList());

        if(cityList.size()>0){
            dataList.clear();
            for(City province :cityList){
                dataList.add(province.getName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel=City.CityType.province;

        }else{

            queryFromServer(cityUrl,"province");

        }
    }

    /**
     * 查询选中省内所有的市，优先从数据库查询，如果没有查询到再去服务器上查询。
     */
    private void queryCities() {
        titleText.setText(selectedProvince.getName());
        backButton.setVisibility(View.VISIBLE);
//        cityList = LitePal.where("cityType=?", City.CityType.city.ordinal()+"")
//                .where("name=?",selectedProvince.getName()).find(City.class);
        cityList = cityAllList.stream()
                .filter(item -> item.getCityType()==City.CityType.city.ordinal()&& item.getParentName()==selectedProvince.getName()).collect(Collectors.toList());
        if(cityList.size()>0){
            dataList.clear();
            for(City province :cityList){
                dataList.add(province.getName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel=City.CityType.city;

        }else{

            queryFromServer(cityUrl,"city");
        }
    }
    /**
     * 查询选中市内所有的县，优先从数据库查询，如果没有查询到再去服务器上查询。
     */
    private void queryCounties() {
        titleText.setText(selectedCity.getName());
        backButton.setVisibility(View.VISIBLE);

        cityList = cityAllList.stream().filter(item -> item.getCityType()==City.CityType.country.ordinal()&&item.getParentName()==selectedCity.getName())
                .collect(Collectors.toList());
       if(cityList.size()>0){
            dataList.clear();
            for(City province :cityList){
                dataList.add(province.getName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel=City.CityType.country;

        }else{

            queryFromServer(cityUrl,"county");
        }

    }

    /**
     * 根据传入的地址和类型从服务器上查询省市县数据。
     */
    private void queryFromServer(String address,final String type) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new okhttp3.Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                boolean result = false;
                String Js = responseText.split("=")[1];
                Map<String, String> resultData = JsonUtil.JsonStrToObject(Js);
                List<City> LPcity= new ArrayList<>();
                List<City> LCcity= new ArrayList<City>();
                List<City> LYcity= new ArrayList<City>();
                //删除整张表的数据
                LitePal.deleteAll(City.class);
                for (String PMkey : resultData.keySet()) {
                    String PMvalue = resultData.get(PMkey);//省
                    City Pcity =new City();
                    Pcity.setCityType(City.CityType.province);
                    Pcity.setName(PMkey);
                    LPcity.add(Pcity);
                    Map<String, String> CM = JsonUtil.JsonStrToObject(PMvalue);
                    for (String CMkey : CM.keySet()) {
                        String CMvalue = CM.get(CMkey);//城市
                        City Ccity =new City();
                        Ccity.setCityType(City.CityType.city);
                        Ccity.setName(CMkey);
                        Ccity.setParentName(PMkey);
                        LCcity.add(Ccity);
                        Map<String, String> CoM = JsonUtil.JsonStrToObject(CMvalue);
                        for (String CoMkey : CoM.keySet()) {
                            String CoMvalue = CoM.get(CoMkey);//县市
                            Map<String, String> CyM = JsonUtil.JsonStrToObject(CoMvalue);
                            City Cycity =new City();
                            Cycity.setCityType(City.CityType.country);
                            Cycity.setName(CoMkey);
                            Cycity.setParentName(CMkey);
                            Cycity.setId(CyM.get("AREAID"));
                            LYcity.add(Cycity);

                        }
                    }
                }
                cityAllList.clear();
                cityAllList.addAll(LPcity);
                cityAllList.addAll(LCcity);
                cityAllList.addAll(LYcity);
                if (true) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvinces();
                            } else if ("city".equals(type)) {
                                queryCities();
                            } else if ("county".equals(type)) {
                                queryCounties();
                            }
                        }
                    });
                }

            }











            @Override
            public void onFailure(Call call, IOException e) {
                // 通过runOnUiThread()方法回到主线程处理逻辑
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }


    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

}